

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author feng
 * @Date 2021/12/4 17:06
 * stream的终止操作
 * 规约
 */
public class StreamTest02 {

    @Test
    public void test2() {
        List<Employee> employees = EmployeeData.getEmployees();
        //检查所有匹配的元素，返回值为boolean类型
        boolean b = employees.stream().allMatch(e -> e.getAge() > 15);
        System.out.println(b);
        System.out.println();
        //2.检查是否匹配一个元素
        boolean b1 = employees.stream().anyMatch(e -> e.getSalary() > 10000);
        System.out.println("是否大于10000" + "    " + b1);
        System.out.println();
        //3.检查没有元素
        boolean b2 = employees.stream().noneMatch(e -> e.getName().contains("雷"));
        System.out.println("b2=" + b2);
        System.out.println();
        // 4.返回第一个元素
        Optional<Employee> employee = employees.stream().findFirst();
        System.out.println("第一个元素" + employee);
        System.out.println();
        // 5.返回当前流中任意元素
        Optional<Employee> employee1 = employees.stream().findAny();
        System.out.println("employee" + employee1);
    }

    @Test
    public void test() {
        //返回流中元素的个数
        List<Employee> employees = EmployeeData.getEmployees();
        long count = employees.stream().filter(e -> e.getSalary() > 5000).count();
        System.out.println("大于5000的员工" + count);
        //返回最高的工资
        Optional<Double> max = employees.stream().map(e -> e.getSalary()).max((d1, d2) -> Double.compare(d1, d2));
        System.out.println(max);
        //返回员工最低的工资
        Optional<Employee> min = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println("工资最低的员工" + min);
        //foreach
        employees.stream().forEach(System.out::println);
    }

    /**
     * 归约
     */
    @Test
    public void test02() {
        //可以将流中的值返回结合起来，
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        Integer reduce = list.stream().reduce(0, (e1, e2) -> Integer.sum(e1, e2));
        System.out.println(reduce);
        System.out.println();

        List<Employee> list1 = EmployeeData.getEmployees();
        Optional<Double> reduce1 = list1.stream().map(e1 -> e1.getSalary()).reduce(Double::max);
        System.out.println("最高" + reduce1);
    }

    /**
     * 收集
     */
    @Test
    public void test03() {
        List<Employee> employees = EmployeeData.getEmployees();
        List<Employee> list = employees.stream().filter(e -> e.getSalary() > 5000).collect(Collectors.toList());
        list.forEach(System.out::println);

    }
}










